const chokidar = require('chokidar')
const path = require('path')

const mockDir = path.join(process.cwd(), 'mock')

// 删除对应的接口路由缓存
function removeRegisterRoutes() {
  Object.keys(require.cache).forEach(i => {
    if (i.includes(mockDir)) {
      console.log(i)
      delete require.cache[require.resolve(i)]
    }
  })
}
// 注册接口路由
function registerRoutes(app){
  const mocks = require('./index') // 这里必须在函数内引用，否则无法实现热更新
  let count = 0
  for (const mock of mocks) {
    app[mock.method](mock.url, mock.response);
    count++
  }
  return {
    start: app._router.stack.length - count,
    count
  }
}

module.exports = (app) => {
  let { start, count } = registerRoutes(app)
  chokidar.watch(mockDir, {}).on('all', (event, path) => {
    if (event === 'change' || event === 'add') {
      console.log(9999)
      app._router.stack.splice(start, count)
      removeRegisterRoutes()
      const stack = registerRoutes(app)
      start = stack.start
      count = stack.count
    }
  })
}